package com.treetao.union.db.service.impl;

import com.treetao.union.db.model.MallSkill;
import com.treetao.union.db.model.MallSkillSku;
import com.treetao.union.db.mapper.MallSkillMapper;
import com.treetao.union.db.service.MallSkillService;
import com.treetao.union.db.service.MallSkillSkuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 秒杀活动 服务实现类
 * </p>
 *
 * @author Dev.M
 * @since 2020-05-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MallSkillServiceImpl extends ServiceImpl<MallSkillMapper, MallSkill> implements MallSkillService {

	@Autowired
	private MallSkillSkuService mallSkillSkuService;
	
	@Override
	public MallSkill getAvaliableSkill() {
		Date cur = new Date();
		QueryWrapper<MallSkill> q = new QueryWrapper<MallSkill>();
		q.eq("del_flag", false);
		q.le("startTime", cur);
		q.ge("endTime", cur);
		return getOne(q);
	}
	
	@Override
	public Boolean started(Long skillId) {
		Date cur = new Date();
		QueryWrapper<MallSkill> q = new QueryWrapper<MallSkill>();
		q.eq("del_flag", false);
		q.eq("id", skillId);
		q.le("startTime", cur);
		q.ge("endTime", cur);
		return count(q) > 0;
	}

	@Override
	public List<MallSkillSku> getSkillSkus(Long skillId) {
		QueryWrapper<MallSkillSku> q = new QueryWrapper<MallSkillSku>();
		q.eq("del_flag", false);
		q.eq("skillId", skillId);
		return mallSkillSkuService.list(q);
	}

	@Override
	public MallSkillSku getSkillSku(Long skillId,Long skuId) {
		QueryWrapper<MallSkillSku> q = new QueryWrapper<MallSkillSku>();
		q.eq("del_flag", false);
		q.eq("skillId", skillId);
		q.eq("skuId", skuId);
		MallSkillSku skillSku = mallSkillSkuService.getOne(q);
		if(skillSku!=null) {
			Map<String, Object> exts = new HashMap<String, Object>();
			exts.put("skill", getById(skillId));
			skillSku.setExts(exts);
		}
		return skillSku;
	}

	@Override
	public Long isExistBetweenTime(Date startTime, Date endTime) {
		QueryWrapper<MallSkill> q = new QueryWrapper<MallSkill>();
		q.eq("del_flag", false);
		q.between("startTime", startTime, endTime);
		q.or().between("endTime", startTime, endTime);
		List<MallSkill> skills = list(q);
		if(skills!=null && skills.size()>0) {
			MallSkill skill = skills.get(0);
			if(skill!=null) return skill.getId();
		}
		
		return null;
	}

	@Override
	public Boolean existSkilling(Long skuId) {
		MallSkill skill = getAvaliableSkill();
		if(skill!=null) {
			MallSkillSku sku = getSkillSku(skill.getId(), skuId);
			if(sku!=null) {
				return true;
			}
		}
		return false;
	}
	
}
